package com.app.milkteaapp.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.app.milkteaapp.bean.LoginGsonBean;
import com.app.milkteaapp.R;
import com.app.milkteaapp.utils.GsonUtils;
import com.app.milkteaapp.utils.MyTools;
import com.app.milkteaapp.utils.SpUtils;
import com.app.milkteaapp.view.RoundImageView;

import org.jetbrains.annotations.NotNull;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class LoginActivity extends AppCompatActivity implements View.OnClickListener {
    private static final String TAG = "LoginActivity";
    private EditText etUsername;
    private EditText etPassword;
    private Button btnLogin;
    private TextView tvRegister;
    private String username;
    private String password;
    Context context = this;
    private Intent intent;
    private RoundImageView img_round;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        initView();
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.mipmap.n3);
        img_round.setBitmap(bitmap);
    }

    private void initView() {
        etUsername = (EditText) findViewById(R.id.et_username);
        etPassword = (EditText) findViewById(R.id.et_password);
        btnLogin = (Button) findViewById(R.id.btn_login);
        img_round = (RoundImageView) findViewById(R.id.img_round);

        btnLogin.setOnClickListener(this);
        tvRegister = (TextView) findViewById(R.id.tv_register);
        tvRegister.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //点击登录按钮后
            case R.id.btn_login:
                if(submit()){
                    JSONObject jsonObject = new JSONObject();
                    try {
                        jsonObject.put("name",username);
                        jsonObject.put("password",password);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    Log.d(TAG, "onClick: "+jsonObject.toString());
                    OkHttpClient client = new OkHttpClient();

                    MediaType type = MediaType.parse("application/json;charset=utf-8");
                    RequestBody requestBody =RequestBody.create(type,jsonObject.toString());

                    Request request = new Request.Builder()
                            .post(requestBody)
                            .url(MyTools.URL+"/user/login")
                            .build();
                    Call call = client.newCall(request);

                    call.enqueue(new Callback() {
                        @Override
                        public void onFailure(@NotNull Call call, @NotNull IOException e) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(context, "网络炸了", Toast.LENGTH_SHORT).show();
                                }
                            });
                        }

                        @Override
                        public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                            //gson解析
                            String string = response.body().string();
                            final LoginGsonBean loginGsonBean = GsonUtils.fromJson(string, LoginGsonBean.class);

                            //告诉用户登录的情况
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(context, loginGsonBean.getMassage(), Toast.LENGTH_SHORT).show();
                                }
                            });

                            //如果请求成功,则将用户存入sp并跳转主页
                            if (loginGsonBean.isSuccess()) {
                                SpUtils.putUserBean(context,loginGsonBean.getData());
                                intent = new Intent(LoginActivity.this,HomepageActivity.class);
                                startActivity(intent);
                                finish();
                            }
                        }
                    });
                }
                break;

            //点击注册按钮后
            case R.id.tv_register:
                intent = new Intent(LoginActivity.this,RegisterActivity.class);
                startActivity(intent);
                break;

        }
    }

    private boolean submit() {
        // validate
        username = etUsername.getText().toString().trim();
        password = etPassword.getText().toString().trim();
        if (TextUtils.isEmpty(username)) {
            Toast.makeText(this, "username不能为空", Toast.LENGTH_SHORT).show();
        }else if (TextUtils.isEmpty(password)) {
            Toast.makeText(this, "password不能为空", Toast.LENGTH_SHORT).show();
        }else {
            return true;
        }
        return false;

    }
}
